package com.demo.http;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class HttpClientDemo {
    private static AtomicInteger count = new AtomicInteger(0);

    public static String postRequest(String url, String message) throws UnsupportedEncodingException {

        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

                if (executionCount >= 5) {
                    return false;
                }

                if (exception instanceof InterruptedIOException) {
                    return false;
                }

                if (exception instanceof UnknownHostException) {
                    return false;
                }

                if (exception instanceof ConnectTimeoutException) {
                    return false;
                }

                if (exception instanceof SSLException)
                {
                    return false;
                }
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    // Retry if the request is considered idempotent

                    System.out.println("retry connect");
                    request.addHeader("retry","connect retry");
                    return true;
                }

                if (exception instanceof ConnectException)
                {

                    System.out.println("retry connecting");
                    return true;
                }
                return false;
            }
        };
        CloseableHttpClient httpClient = HttpClients.custom()
                .setRetryHandler(httpRequestRetryHandler)
                .build();

        HttpPost httpPost = new HttpPost(url);
//
//        List<NameValuePair> nvps = Lists.newArrayList();
//        int countValue = count.incrementAndGet();
//        String value = String.valueOf(countValue);
//        nvps.add(new BasicNameValuePair("key1","hello"));
//        nvps.add(new BasicNameValuePair("key2","server"));
//        nvps.add(new BasicNameValuePair("key3",value));
//        httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        String jsonParams = "hello man";
        Map<String,String> jobConf = Maps.newHashMap();
        jobConf.put("jobName","testJob");
        jobConf.put("jobId","1234567");
        jobConf.put("jobStatus","ok");
        Message message1 = new Message();
        message1.setType(1);
        message1.setInfo("hello man");

        JobResult jobResult = new JobResult("123456");
        jobResult.setErrDesc("hello error");
        jobResult.setRunServer("172.168.1.1");

        JobConf jobConf1 = new JobConf();

        jobConf1.set("1","hello");
        jobConf1.set("2","hello");
        jobConf1.set("3","hello");

        jobResult.setJobConf(jobConf1);

        jsonParams = JSONObject.toJSONString(jobResult);
        StringEntity uefEntity = new StringEntity(jsonParams, "UTF-8");

        SerializableEntity serializableEntity = new SerializableEntity(new Message(1, jobConf));
        httpPost.setEntity(uefEntity);
        httpPost.setHeader("ip","192.168.1.1");
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);

            StatusLine statusLine = response.getStatusLine();
            System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());

            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();

            BufferedInputStream bis = new BufferedInputStream(content);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int result = bis.read();

            while (result != -1)
            {
                baos.write(result);
                result = bis.read();
            }
            System.out.println("----"+baos.toString());
            boolean isSuccess = Boolean.parseBoolean(baos.toString());
            System.out.println("server response : "+isSuccess);
            if (statusLine.getStatusCode() == 200)
            {
                return "success";
            }
        } catch (IOException  e) {
            e.printStackTrace();
        }
        return "fail";
    }
}
